package com.xiaow.springsecuriydemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.protocol.ResultsetRow;
import com.xiaow.springsecuriydemo.entity.User;
import com.xiaow.springsecuriydemo.entity.Userandrole;
import com.xiaow.springsecuriydemo.service.LoginService;
import com.xiaow.springsecuriydemo.service.UserService;
import com.xiaow.springsecuriydemo.service.UserandroleService;
import com.xiaow.springsecuriydemo.utils.JwtUtils;
import com.xiaow.springsecuriydemo.vo.Result;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @ClassName LoginController
 * @Author xiaow
 * @DATE 2022/9/15 10:11
 **/
@RestController
public class LoginController {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    LoginService loginService;
    @Autowired
    UserService userService;
    @Autowired
    UserandroleService userandroleService;

    /**
     * 普通用户登录接口
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {

        String username = user.getUsername();
        Userandrole byUserName = userandroleService.getByUserName(username);
        if (!Objects.isNull(byUserName)) {
            Integer roleid = byUserName.getRoleid();
            if (roleid.equals(2)) {
                return loginService.login(user);
            }
        }
        return Result.fail("账号或密码错误");
    }


    /**
     * 商家登录接口
     *
     * @param user
     * @return
     */
    @PostMapping("/shoper/login")
    public Result shoperLogin(@RequestBody User user) {
        String username = user.getUsername();
        Userandrole byUserName = userandroleService.getByUserName(username);
        if (!Objects.isNull(byUserName)) {
            Integer roleid = byUserName.getRoleid();
            if (roleid.equals(3)) {
                return loginService.login(user);
            }
        }
        return Result.fail("账号或密码错误");

    }

    @GetMapping("/user/logout")
    public Result logout() {
        return loginService.logout();
    }


    /**
     * 获取用户状态
     * @return
     */
    @GetMapping("/user/state")
    public Result getState(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");
        if(Strings.isEmpty(token))
            return Result.fail("未登录");
        Claims claims = JwtUtils.getClaims(token);
        User o = (User) redisTemplate.opsForValue().get("login" + claims.get("userid"));
        o.setPassword("");
        if(Objects.isNull(o)){
            return Result.fail("未登录");
        }else{
            return Result.succ(o);
        }
    }
}
